define(["jquery","template","bbcare","comm/form/decode"],function($,template,$bb,$decode){
	var quest = {};
	var URL = $bb.baseUrl("followapp");

	/**
	 * tpl模板
	 */
	quest.tpl = function(){
		return 	'<script id="tpl_question_autocomplete" type="text/html">'+
				'	<div {{if relationId}}relationId="{{relationId}}"{{/if}} class="qaCard form-group form-group-sm col-sm-{{length}} col-md-{{length}} grid-label-{{labelLength}}">'+
				'		<label class="control-label {{align}}">{{label}}</label>'+
				'   	<div class="control-input qaCard-autocomplete">'+
				'			{{if status=="default"}}'+
				'   			<input type="text" class="form-control validatebox" name="{{name}}" data-searchUserUrl="{{searchUserUrl}}" data-searchValueUrl="{{searchValueUrl}}" data-type="{{type}}" data-quesId="{{id}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" data-dataUnit="{{dataUnit}}" placeholder="{{placeHolder}}" data-validate="{{validate}}" data-attention="{{attention}}" autocomplete="off">'+
				'				<div class="patientsList"></div>'+
				'			{{else if status=="readonly"}}'+
				'				<p class="form-control-static validatebox" name="{{name}}" data-searchUserUrl="{{searchUserUrl}}" data-searchValueUrl="{{searchValueUrl}}" data-type="{{type}}" data-quesId="{{id}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" data-dataUnit="{{dataUnit}}" data-validate="{{validate}}" data-attention="{{attention}}"></p>'+
				'			{{else if status=="disabled"}}'+
				'   			<input type="text" class="form-control validatebox" name="{{name}}" data-searchUserUrl="{{searchUserUrl}}" data-searchValueUrl="{{searchValueUrl}}" data-type="{{type}}" data-quesId="{{id}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" data-dataUnit="{{dataUnit}}" placeholder="{{placeHolder}}" data-validate="{{validate}}" data-attention="{{attention}}" disabled>'+
				'			{{/if}}'+
				'		</div>'+
				'	</div>'+
				'</script>';
	}

	/**
	 * 赋值
	 */
	quest.setValue = function($dom,value){
		if( value ){
			$dom.hasClass("form-control-static") ? $dom.html(value.quesValue) : $dom.val(value.quesValue);
		}
	}

	/**
	 * 获取value（保存时，获取每个dom对应的答案）
	 */
	quest.getValue = function($dom,name){
		var value = {};
		value.quesValue = $dom.hasClass("form-control-static") ? $dom.html() : $dom.val();
		value.quesId = $dom.attr("data-quesId");
		value.deCode = $dom.attr("data-deCode");
		value.innDeCode = $dom.attr("data-innDeCode");
		var dataUnit = $dom.attr("data-dataUnit");
		if( dataUnit ) value.dataUnit = dataUnit;
		return value;
	}

	/**
	 * 事件(若没有事件函数，可以不写)
	 * 		需要用到eventParams参数中的3个参数：autocompleteCallBack、autoCompleteParams
	 */
	quest.event = function(eventParams,id){
		if( eventParams ){
			$("#" + id + " .qaCard-autocomplete input").unbind("input propertychange");
		    $("#" + id + " .qaCard-autocomplete input").data({"eventParams":eventParams});
		    $("#" + id + " .qaCard-autocomplete input").bind("input propertychange",onPatientsByPhone);
		}
	}

	/******************** event ********************/

	/**
	 * 根据手机号码查询患者
	 */
	var onPatientsByPhone = function(){
		if( $bb.getIocalStorage("version") == "online" ){
			var eventParams = $(this).data("eventParams");
			var deCode = $(this).attr("data-deCode");
			var value = $(this).val();
			var params = {};
			if( $.trim(value) != '' ){
				switch(deCode){
					case $decode.getDeCodeByName("userName"):
						$.extend(params,{"userName":value});
						break;
					case $decode.getDeCodeByName("phoneNo"):
						$.extend(params,{"phoneNo":value});
						break;
					case $decode.getDeCodeByName("hisNo"):
						$.extend(params,{"hisNo":value});
						break;
					case $decode.getDeCodeByName("userName"):
						$.extend(params,{"idCard":value});
						break;
				}
				if( !$.isEmptyObject(params) ) ajaxSearchUser(params,ajaxSearchUserCallBack,$(this),eventParams);
			}else{
				$(this).next(".patientsList").css({"display":"none"});
			}
		}
	};

	/**
     * 根据手机号码、姓名、编号、身份证号
     */
    var ajaxSearchUser = function(params,callback,$dom,eventParams){
		var url = $dom.attr("data-searchUserUrl");
		if( !url ) url = "ctrl/ptmanage/patientQueryByPhoneNum";
        $bb.ajax({
            url: URL + url,
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    data.data ? callback(data.data,$dom,eventParams) : callback(data,$dom,eventParams);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "根据手机号、姓名、档案编号、身份证号查询患者信息出错！");
                }
            }
        });
    };

    /**
     * 根据手机号码、姓名、编号、身份证号查询患者成功后的回调函数
     */
    var ajaxSearchUserCallBack = function(data,$dom,eventParams){
    	if( data.rows.length > 0 ){
			$dom.next(".patientsList").css({"display":"block"});
			patientListUi({
				"dom":$dom.next(".patientsList"),
				"rows":data.rows
			});
			$(document).click(function(){
				$dom.next(".patientsList").css({"display":"none"});
			});
			$dom.next(".patientsList").find(".addPatientBtn").click(function(){
				$dom.next(".patientsList").css({"display":"none"});
			});
			$dom.next(".patientsList").find(".patient-item").unbind("click");
			$dom.next(".patientsList").find(".patient-item").click(function(){
				var userId = $(this).attr("data-userId");
				var regTaskId = $(this).attr("data-regTaskId");
				var params = { "userId":userId };
				if( regTaskId ) $.extend(params,{"regTaskId":regTaskId});
				ajaxArchiveContent(params,$dom,ajaxArchiveContentCallBack,eventParams);
			});
		}else{
			$dom.next(".patientsList").css({"display":"none"});
		}
    }

    // ui
	var patientListUi = function(options){
		options.dom.html( patientListTpl() );
		var h = template("tpl_question_autocomplete_patientList",options);
		options.dom.html(h);
	}

	//tpl
	var patientListTpl = function(){
		return 	'<script id="tpl_question_autocomplete_patientList" type="text/html">'+
				'	<ul>'+
				'		<li class="addPatientBtn"><i class="fa fa-plus"></i>添加</li>'+
				'		{{each rows as value i}}'+
				'		<li class="patient-item" data-userId="{{if value.userId}}{{value.userId}}{{else}}{{value.id}}{{/if}}" {{if value.regTaskId}}data-regTaskId="{{value.regTaskId}}"{{/if}}>'+
				'			{{value.userName}}'+
				' 			({{if value.gender == "F"}}'+
				'				<span class="girl">女孩</span>'+
				'			{{else if value.gender == "M"}}'+
				'				<span class="boy">男孩</span>'+
				'			{{/if}})'+
				'		</li>'+
				'		{{/each}}'+
				'	</ul>'+
				'</script>';
	}
	
	/**
     * 查询建档答案
     */
    var ajaxArchiveContent = function(params,$dom,callback,eventParams){
    	var url = $dom.attr("data-searchValueUrl");
		if( !url ) url = "ctrl/ptmanage/qryArchiveTaskById";
        $bb.ajax({
            url: URL + url,
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data.data,eventParams);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "查询建档答案出错！");
                }
            }
        })
    };

    /**
     * 查询建档答案成功后的回调函数
     */
    var ajaxArchiveContentCallBack = function(data,eventParams){
    	if( eventParams.autoCompleteCallBack && typeof eventParams.autoCompleteCallBack == "function" ){
			eventParams.autoCompleteCallBack(data,eventParams.autoCompleteParams);
		}
    }

	return quest;
});